package com.whitedust.top80;

import java.util.Arrays;

/**
 *
 * @author A
 * @since 2025/11/15 23:29
 */

public class Top75 {
    int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};


    private int dfs(int[][] grid, int[][] visited, int x, int y) {
        if (grid[x][y] == 0 || visited[x][y] == 1) return 0;
        visited[x][y] = 1;
        int area = 1;
        for (int i = 0; i < 4; i++) {
            int nextX = x + dir[i][0];
            int nextY = y + dir[i][1];
            if (nextX < 0 || nextY < 0 || nextX >= grid.length || nextY >= grid[0].length) continue;
            area += dfs(grid, visited, nextX, nextY);
        }
        return area;
    }

    public int maxAreaOfIsland(int[][] grid) {
        int[][] visited = new int[grid.length][grid[0].length];
        for (int[] visit : visited) {
            Arrays.fill(visit, 0);
        }
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1 && visited[i][j] == 0) {
                    int dfs = dfs(grid, visited, i, j);
                    res = Math.max(dfs, res);
                }
            }
        }
        return res;
    }
}
